<?php
namespace Home\Controller;

use Home\Model\UserModel;
use Home\Model\Webchat;
use Home\Model\Setting;

class SiteController extends BaseController {

    public function index(){
        $this->display('index');
    }

    public function webchatMenu() {
        $menu = null;
        $we = new Webchat();

        if (IS_POST) {
            $menu = htmlspecialchars_decode(I('webchat_menu'));
            $menu = json_decode($menu, true);
            
            if ($we->webchat->createMenu($menu)) {

                $this->redirect('site/webchatMenu', '', 2, '设置成功！');
            }

            $menu = I('webchat_menu');
            $this->assign('error', $we->webchat->errMsg);

        } else {
            $m = $we->webchat->getMenu();
            $menu = json_encode($m['menu'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

        }

        $this->assign('menu', $menu);

        $this->display('webchatMenu');
    }

    public function msg() {
        $this->display('msg');
    }

    public function setting() {
        $setting = null;

        if (IS_POST) {
            foreach ($_POST['Setting'] as $key => $value) {
                Setting::setOption($key, $value);
            }

            $this->redirect('site/setting', '', 2, '设置成功！');
            // $setting = $_POST['Setting'];
        } else {
            $setting['token'] = Setting::getOption('token');
            $setting['encodingaeskey'] = Setting::getOption('encodingaeskey');
            $setting['appid'] = Setting::getOption('appid');
            $setting['appsecret'] = Setting::getOption('appsecret');
        }
        
        $this->assign('setting', $setting);
        
        $this->display('setting');
    }

    public function data() {
        $UserModel = D('UserData');
        
        $this->data = $UserModel->relation(true)->select();

        $this->display('data');
    }

    public function login() {
    	if (IS_POST) {
    		$user = D('User');
    		$username = I('username');
    		$user->where(['username'=>$username])->find();

    		if ($user && $user->login(I('password'))) {
    			$this->redirect('site/index', '', 2, '登陆成功！');
    		}
    	}
    	$this->display('login');
    }

    public function logout() {
    	session(null);

    	$this->redirect('site/login', '', 2, '登出成功！');
    }
}